// 简化的Go隧道管理器Flutter绑定
// 只提供基本的接口调用，所有复杂逻辑由Go实现

import 'dart:ffi';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:ffi/ffi.dart';
import 'package:flutter/foundation.dart';

// 导出FFI类型供其他文件使用
export 'dart:ffi' show Pointer;
export 'package:ffi/ffi.dart' show Utf8;

// 回调函数类型定义
typedef StateChangeCallbackC = Void Function(Pointer<Utf8> state, Pointer<Utf8> message);
typedef StateChangeCallbackDart = void Function(Pointer<Utf8> state, Pointer<Utf8> message);

typedef ProgressCallbackC = Void Function(Double progress, Double speed);
typedef ProgressCallbackDart = void Function(double progress, double speed);

typedef ErrorCallbackC = Void Function(Pointer<Utf8> error);
typedef ErrorCallbackDart = void Function(Pointer<Utf8> error);

// Go函数类型定义
typedef SetCallbacksC = Void Function(
  Pointer<NativeFunction<StateChangeCallbackC>>,
  Pointer<NativeFunction<ProgressCallbackC>>,
  Pointer<NativeFunction<ErrorCallbackC>>
);
typedef SetCallbacksDart = void Function(
  Pointer<NativeFunction<StateChangeCallbackC>>,
  Pointer<NativeFunction<ProgressCallbackC>>,
  Pointer<NativeFunction<ErrorCallbackC>>
);

typedef CreateAndConnectTunnelC = Int32 Function(
  Pointer<Utf8> tunnelID,
  Pointer<Utf8> tunnelServerHost,
  Int32 tunnelServerPort,
  Pointer<Utf8> targetHost,
  Int32 targetPort
);
typedef CreateAndConnectTunnelDart = int Function(
  Pointer<Utf8> tunnelID,
  Pointer<Utf8> tunnelServerHost,
  int tunnelServerPort,
  Pointer<Utf8> targetHost,
  int targetPort
);

typedef DisconnectTunnelC = Int32 Function();
typedef DisconnectTunnelDart = int Function();

typedef IsConnectedC = Int32 Function();
typedef IsConnectedDart = int Function();

typedef GetVersionC = Pointer<Utf8> Function();
typedef GetVersionDart = Pointer<Utf8> Function();

typedef SetLogLevelC = Int32 Function(Int32 level);
typedef SetLogLevelDart = int Function(int level);

typedef GetStatsC = Pointer<Utf8> Function();
typedef GetStatsDart = Pointer<Utf8> Function();

typedef DestroyManagerC = Int32 Function();
typedef DestroyManagerDart = int Function();

/// 简化的隧道管理器绑定
class SimpleTunnelBindings {
  static DynamicLibrary? _library;
  static bool _initialized = false;

  /// 异步初始化动态库
  static Future<void> initialize() async {
    if (_initialized) return;

    try {
      _library = await _loadLibrary();
      _initialized = true;
      debugPrint('✅ 简化Go隧道管理器绑定初始化成功');
    } catch (e) {
      debugPrint('❌ 简化Go隧道管理器绑定初始化失败: $e');
      rethrow;
    }
  }

  /// 加载动态库（支持所有平台）
  static Future<DynamicLibrary> _loadLibrary() async {
    debugPrint('🔍 检测平台: ${Platform.operatingSystem} ${Platform.version}');
    
    String libraryName = '';  // 初始化为空字符串，避免未赋值使用
    String libraryPath = '';
    
    try {
      // 🍎 macOS
      if (Platform.isMacOS) {
        if (Platform.version.contains('arm64')) {
          libraryName = 'libsimple_tunnel_darwin_arm64.dylib';
          debugPrint('🍎 macOS平台 (Apple Silicon)');
        } else {
          libraryName = 'libsimple_tunnel_darwin_amd64.dylib';
          debugPrint('🍎 macOS平台 (Intel)');
        }
        
        // 从资源中提取动态库
        libraryPath = await _extractLibraryFromAssets(libraryName);
        return DynamicLibrary.open(libraryPath);
      }
      
      // 🐧 Linux
      else if (Platform.isLinux) {
        if (Platform.version.contains('aarch64') || Platform.version.contains('arm64')) {
          libraryName = 'libsimple_tunnel_linux_arm64.so';
          debugPrint('🐧 Linux平台 (ARM64)');
        } else {
          libraryName = 'libsimple_tunnel_linux_amd64.so';
          debugPrint('🐧 Linux平台 (x86_64)');
        }
        
        // 从资源中提取动态库
        libraryPath = await _extractLibraryFromAssets(libraryName);
        return DynamicLibrary.open(libraryPath);
      }
      
      // 🪟 Windows
      else if (Platform.isWindows) {
        libraryName = 'simple_tunnel_windows_amd64.dll';
        debugPrint('🪟 Windows平台 (x86_64)');
        
        // 从资源中提取动态库
        libraryPath = await _extractLibraryFromAssets(libraryName);
        return DynamicLibrary.open(libraryPath);
      }
      
      // 🤖 Android
      else if (Platform.isAndroid) {
        // Android会根据ABI自动选择正确的.so文件
        // 从jniLibs目录加载（无需指定路径）
        libraryName = 'simple_tunnel';  // 不需要lib前缀和.so后缀
        debugPrint('🤖 Android平台（自动选择ABI）');
        debugPrint('   支持的ABI: armeabi-v7a, arm64-v8a, x86, x86_64');
        
        // Android直接从jniLibs加载，不需要提取
        return DynamicLibrary.open('libsimple_tunnel.so');
      }
      
      // 📱 iOS
      else if (Platform.isIOS) {
        // iOS使用静态库，在编译时链接
        // 需要在Xcode项目中配置
        libraryName = 'simple_tunnel';
        debugPrint('📱 iOS平台（静态库）');
        debugPrint('   注意：iOS需要在Xcode中配置静态库链接');
        
        // iOS静态库不需要open，使用process方法
        return DynamicLibrary.process();
      }
      
      // ❌ 不支持的平台
      else {
        throw UnsupportedError(
          '不支持的平台: ${Platform.operatingSystem}\n'
          '支持的平台: macOS, Linux, Windows, Android, iOS'
        );
      }
    } catch (e) {
      debugPrint('❌ 加载动态库失败: $libraryName');
      debugPrint('   错误详情: $e');
      
      // 提供友好的错误信息
      if (Platform.isAndroid) {
        throw Exception(
          '无法加载Android动态库\n'
          '请确保.so文件已正确复制到以下目录:\n'
          '  - android/app/src/main/jniLibs/armeabi-v7a/\n'
          '  - android/app/src/main/jniLibs/arm64-v8a/\n'
          '  - android/app/src/main/jniLibs/x86/\n'
          '  - android/app/src/main/jniLibs/x86_64/\n'
          '原始错误: $e'
        );
      } else if (Platform.isIOS) {
        throw Exception(
          '无法加载iOS静态库\n'
          '请在Xcode中执行以下步骤:\n'
          '  1. 将.a文件添加到项目\n'
          '  2. 在Build Phases -> Link Binary With Libraries中添加\n'
          '  3. 确保架构匹配（真机/模拟器）\n'
          '原始错误: $e'
        );
      } else {
        throw Exception('无法加载动态库: $libraryName\n原始错误: $e');
      }
    }
  }

  /// 从Flutter资源中提取动态库到临时目录
  static Future<String> _extractLibraryFromAssets(String libraryName) async {
    try {
      debugPrint('📦 开始提取动态库: $libraryName');
      
      // 从资源中读取动态库数据
      final ByteData data = await rootBundle.load('assets/libs/$libraryName');
      final Uint8List bytes = data.buffer.asUint8List();
      
      debugPrint('   文件大小: ${bytes.length} bytes (${(bytes.length / 1024 / 1024).toStringAsFixed(2)} MB)');

      // 获取临时目录
      final Directory tempDir = await getTemporaryDirectory();
      final String libraryPath = '${tempDir.path}/$libraryName';

      // 写入临时文件
      final File libraryFile = File(libraryPath);
      await libraryFile.writeAsBytes(bytes, flush: true);
      
      debugPrint('   临时路径: $libraryPath');

      // 设置执行权限（Unix系统）
      if (Platform.isLinux || Platform.isMacOS) {
        final result = await Process.run('chmod', ['+x', libraryPath]);
        if (result.exitCode == 0) {
          debugPrint('   ✅ 执行权限已设置');
        } else {
          debugPrint('   ⚠️  设置执行权限失败: ${result.stderr}');
        }
      }

      debugPrint('✅ 动态库提取完成: $libraryPath');
      return libraryPath;
    } catch (e, stackTrace) {
      debugPrint('❌ 提取动态库失败: $libraryName');
      debugPrint('   错误: $e');
      debugPrint('   堆栈: ${stackTrace.toString().split('\n').take(3).join('\n')}');
      
      throw Exception(
        '无法从资源中提取动态库: $libraryName\n'
        '请确保文件已添加到pubspec.yaml的assets中:\n'
        '  assets:\n'
        '    - assets/libs/$libraryName\n'
        '原始错误: $e'
      );
    }
  }

  /// 获取动态库实例
  static DynamicLibrary get library {
    if (_library == null) {
      throw StateError('SimpleTunnelBindings未初始化，请先调用initialize()');
    }
    return _library!;
  }

  // 函数绑定 - 所有函数都是异步获取
  static Future<SetCallbacksDart> get setCallbacks async {
    await initialize();
    return library.lookupFunction<SetCallbacksC, SetCallbacksDart>('SetCallbacks');
  }

  static Future<CreateAndConnectTunnelDart> get createAndConnectTunnel async {
    await initialize();
    return library.lookupFunction<CreateAndConnectTunnelC, CreateAndConnectTunnelDart>('CreateAndConnectTunnel');
  }

  static Future<DisconnectTunnelDart> get disconnectTunnel async {
    await initialize();
    return library.lookupFunction<DisconnectTunnelC, DisconnectTunnelDart>('DisconnectTunnel');
  }

  static Future<IsConnectedDart> get isConnected async {
    await initialize();
    return library.lookupFunction<IsConnectedC, IsConnectedDart>('IsConnected');
  }

  static Future<GetVersionDart> get getVersion async {
    await initialize();
    return library.lookupFunction<GetVersionC, GetVersionDart>('GetVersion');
  }

  static Future<SetLogLevelDart> get setLogLevel async {
    await initialize();
    return library.lookupFunction<SetLogLevelC, SetLogLevelDart>('SetLogLevel');
  }

  static Future<GetStatsDart> get getStats async {
    await initialize();
    return library.lookupFunction<GetStatsC, GetStatsDart>('GetStats');
  }

  static Future<DestroyManagerDart> get destroyManager async {
    await initialize();
    return library.lookupFunction<DestroyManagerC, DestroyManagerDart>('DestroyManager');
  }
}
